package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.BaseException;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;
    /**
     * 新增菜品
     * @param dishDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class) // 开启事务
    public void addDish(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.insertDish(dish);

        // 插入口味信息
        List<DishFlavor> flavors = dishDTO.getFlavors();
        flavors.forEach(item -> {
            item.setDishId(dish.getId());
        });
        dishFlavorMapper.insertFlavor(flavors);
    }

    /**
     * 菜品分页查询
     * @param pageQueryDTO
     * @return
     */
    @Override
    public PageResult dishPageQuery(DishPageQueryDTO pageQueryDTO) {
        PageHelper.startPage(pageQueryDTO.getPage(),pageQueryDTO.getPageSize());
        Dish dish = Dish.builder().categoryId(pageQueryDTO.getCategoryId())
                .name(pageQueryDTO.getName())
                .status(pageQueryDTO.getStatus())
                .build();
        Page<DishVO> page = dishMapper.pageQuery(dish);
        return new PageResult(page.getTotal(),page.getResult());
    }


    /**
     * 根据id查询菜品
     * @param id
     * @return
     */
    @Override
    public DishVO queryDishByIdWithFlavor(Long id) {
        // 根据id查询菜品数据
        Dish dish = dishMapper.getById(id);
        // 根据菜品id查询口味数据
        List<DishFlavor> flavors = dishFlavorMapper.getFlavorByDishId(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(flavors);
        dishVO.setCategoryName(categoryMapper.getById(dish.getCategoryId()).getName());
        return dishVO;
    }


    /**
     * 批量删除菜品
     * @param ids
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByIds(List<Long> ids) {

         // - 可以一次删除一个菜品，也可以批量删除菜品
        // 起售中的菜品不能删除
        List<Dish> dishes = dishMapper.queryDishByIds(ids);
        for (Dish dish : dishes) {
            if (dish.getStatus() == 1) {
                throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ON_SALE);
            }
        }
        // 被套餐关联的菜品不能删除
        List<Long> dishIds = setmealDishMapper.querySetmealByDishIds(ids);
        if (dishIds != null && !dishIds.isEmpty()) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        // 根据ids删除菜品
        dishMapper.deleteDishByIds(ids);
        // 删除菜品后，关联的口味数据也需要删除掉
        dishFlavorMapper.deleteDishFlavorByDishIds(ids);
    }


    /**
     * 更新菜品信息
     * @param dishDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDish(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        // 修改dish信息
        dishMapper.updateDish(dish);
        // 删除原有的flavor信息
        List<Long> list = new ArrayList<>();
        list.add(dish.getId());
        dishFlavorMapper.deleteDishFlavorByDishIds(list);
        // 插入新增的flavor信息
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && !flavors.isEmpty()) {
            flavors.forEach(item -> {
                item.setDishId(dish.getId());
            });
            dishFlavorMapper.insertFlavor(flavors);
        }
    }


    /**
     * 修改菜品状态信息
     * @param status
     * @param id
     */
    @Override
    public void changeStatus(Integer status,Long id) {
        // 如果菜品在启售中的套餐中存在,则不能停售
        Integer count = setmealDishMapper.getCountByDishId(id);
        if (count > 0) {
            throw new BaseException(MessageConstant.DISH_ENABLE_FAILED);
        }
        Dish dish = new Dish();
        dish.setStatus(status);
        dish.setId(id);
        dishMapper.updateDish(dish);
    }


    /**
     * 根据分类id查询菜品
     * @param id
     * @return
     */
    @Override
    public List<Dish> qaueryDishByCategoryId(Long categoryId) {
        return dishMapper.qaueryDishByCategoryId(categoryId);
    }

    /**
     * 根据分类id查询启售的菜品和口味
     * @param categoryId
     * @return
     */
    @Override
    public List<DishVO> qaueryDishAndFlavorByCategoryId(Long categoryId) {
        List<Dish> dishes = dishMapper.qaueryDishByCategoryId(categoryId);
        List<DishVO> dishList = new ArrayList<>();
        for (Dish dish : dishes) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dish,dishVO);

            List<DishFlavor> flavors = dishFlavorMapper.getFlavorByDishId(dish.getId());
            dishVO.setFlavors(flavors);
            dishList.add(dishVO);
        }
        return dishList;
    }
}
